import ReconnectingWebSocket from 'reconnecting-websocket';
import store from '@/store'
import {Notice} from 'iview'
import {seenMessage,getMessageData} from "@/api/data";
import router from "@/router";

export default {
  // 创建 websocket 链接
  createWebsocket(userId) {
    const httpURL = process.env.VUE_APP_DOMAIN;
    this.websocket = new ReconnectingWebSocket(`ws://` + httpURL + `/webSocket/` + userId);
    // 连接发生错误的回调方法
    this.websocket.onerror = this.websocketOnerror;
    // 连接成功建立的回调方法
    this.websocket.onopen = this.websocketOnopen;
    // 接收到消息的回调方法
    this.websocket.onmessage = this.websocketOnmessage;
    // 连接关闭的回调方法
    this.websocket.onclose = this.websocketOnclose;
    // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    this.websocket.onbeforeunload = this.websocketOnbeforeunload;
  },

// 连接发生错误的回调方法
  websocketOnerror() {
    console.log('连接发生错误的回调方法');
  },
// 连接成功建立的回调方法
  websocketOnopen() {

  },
// 接收到消息的回调方法
  websocketOnmessage(event) {
    let obj = JSON.parse(event.data)
    switch (obj.type) {
      case "msg":
        store.commit('setMsgData', obj.data)
        Notice.config({
          duration: 10//消息提示停留10秒
        })
        Notice.info({
          title: obj.data.title,
          name:obj.data.id,
          desc: obj.data.content,
          render: h => {
            return h('span', {
              style: {
                cursor:"pointer"
              },
              on: {
                click: () => {
                  switch (obj.data.msgType) {
                    case 1:
                    case "1":
                      router.push({
                        name: 'activiti-tasks'
                      })
                      break;
                    default:
                      console.log(obj.data)
                      break
                  }
                  seenMessage({id:obj.data.id}).then(res=>{
                    store.commit('setMsgData',[])
                    getMessageData({}).then(res => {
                      if (res.code === '0') {
                        store.commit('setMsgData', res.data)
                        Notice.close(obj.data.id)
                      }
                    })
                  })
                }
              }
          },obj.data.content)
          }
        });
        break;
      default:
        console.log(obj.data)
    }
  },

// 连接关闭的回调方法
  websocketOnclose(event) {
    console.log("连接已关闭")
  },
// 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常
  websocketOnbeforeunload() {
    this.closeWebSocket();
    console.log('监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常');
  },
// 关闭WebSocket连接
  closeWebSocket() {
    this.websocket.close();
  },
}

